﻿using AgencyManagerSystem.AsmType;
using AgencyManagerSystem.Common;
using AgencyManagerSystem.DataFetcher;
using AgencyManagerSystem.DataUpdater;
using AgencyManagerSystem.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;

namespace AgencyManagerSystem.Core
{
    public class OrderManager : MainDetailManager<OrderModel, OrderDetailModel>
    {
        //const string jsonHead = "{{\"Model\": {{\"FID\": \"0\",\"FBillNo\": \"{4}\",\"F_HSH_SRCFID\": \"{5}\",\"FBillTypeID\": {{\"FNUMBER\": \"XSDD01_SYS\"}},\"FDate\": \"{0}\",\"FNote\": \"{3}\",\"FSaleOrgId\": {{\"FNumber\": \"WL01\"}},\"FCustId\": {{\"FCustId\": \"{1}\"}},\"FSalerId\": {{\"FNumber\": \"ROBOT\"}},\"FSaleOrderFinance\": {{\"FSettleCurrId\": {{\"FNumber\": \"PRE001\"}},\"FExchangeRate\":\"1\"}},\"FSaleOrderEntry\": [{2}]}}}}";
        //const string jsonBody = "{{\"FMaterialId\": {{\"FNumber\": \"{0}\"}},\"FUnitID\": {{\"FName\": \"{1}\"}},\"FQty\": \"{2}\",\"FEntryNote\": \"{4}\",\"FPrice\": \"0.01\",\"FDeliveryDate\": \"{3}\",\"FSettleOrgIds\": {{\"FNumber\": \"WL01\"}},\"FOUTLMTUNIT\": \"销售单位\",\"F_HSH_SRCENTRYID\": \"{5}\"}}";

        //const string jsonHead = "{{\"Model\": {{\"FID\": \"0\",\"FBillNo\": \"{4}\",\"F_HSH_SRCFID\": \"{5}\",\"FBillTypeID\": {{\"FNUMBER\": \"XSDD01_SYS\"}},\"FDate\": \"{0}\",\"FNote\": \"{3}\",\"FSaleOrgId\": {{\"FNumber\": \"WL01\"}},\"FCustId\": {{\"FCustId\": \"{1}\"}},\"FSalerId\": {{\"FNumber\": \"ROBOT\"}},\"FSaleOrderFinance\": {{\"FSettleCurrId\": {{\"FNumber\": \"PRE001\"}},\"FExchangeRate\":\"1\"}},\"FSaleOrderEntry\": [{2}]}}}}";
        const string jsonHead = "{{\"IsEntryBatchFill\":\"false\",\"Model\": {{\"FID\": \"0\",\"FBillNo\": \"{4}\",\"F_HSH_SRCFID\": \"{5}\",\"FBillTypeID\": {{\"FNUMBER\": \"XSDD01_SYS\"}},\"FDate\": \"{0}\",\"FNote\": \"{3}\",\"FSaleOrgId\": {{\"FNumber\": \"{6}\"}},\"FCustId\": {{\"FCustId\": \"{1}\"}},\"FSaleOrderFinance\": {{\"FSettleCurrId\": {{\"FNumber\": \"PRE001\"}},\"FExchangeRate\":\"1\"}},\"FSaleOrderEntry\": [{2}]}}}}";
        const string jsonBody = "{{\"FRowType\": \"{6}\",\"FMaterialId\": {{\"FNumber\": \"{0}\"}},\"FUnitID\": {{\"FNumber\": \"{1}\"}},\"FQty\": \"{2}\",\"FEntryNote\": \"{4}\",\"FPrice\": \"0.01\",\"FDeliveryDate\": \"{3}\",\"FSettleOrgIds\": {{\"FNumber\": \"{7}\"}},\"FOUTLMTUNIT\": \"销售单位\",\"F_HSH_SRCENTRYID\": \"{5}\"}}";

        protected override MainDetailUpdater<OrderModel, OrderDetailModel> InjectionMainDetailUpdater()
        {
            var orderUpdaterCreator = new OrderUpdaterCreator();
            var updater = orderUpdaterCreator.CreateOrderUpdaterInstance();
            return updater;
        }
        public override AsmObject<bool> Approve(OrderModel main)
        {
            string bridgePath = Path.GetDirectoryName(this.GetType().Assembly.Location)+"\\bdg\\erpbridge.exe";
            StringBuilder sb = new StringBuilder();
            OrderDetailFetcher orderDetailFetcher = new OrderDetailFetcher();
            bool firstItem = true;
            RetailFetcher retailFetcher = new RetailFetcher();
            var retail = retailFetcher.Get(main.Retail);
            var saleorg = retail.OrderOrg == "0" ? "WL01" : retail.OrderOrg;
            foreach (var item in orderDetailFetcher.ListDetail(main.AutoId))
            {
                if (firstItem)
                {
                    firstItem = false;
                }
                else
                {
                    sb.Append(",");
                }
                string frowtype = "Standard";
                var pd = new ProductionFetcher().Get(item.ProductionId);
                if (pd != null && pd.Suite == "1")
                {
                    frowtype = "Parent";
                }
                ProductionFetcher productionFetcher = new ProductionFetcher();
                var production = productionFetcher.Get(item.ProductionId);
                sb.Append(String.Format(jsonBody,item.ProductionCode,item.OrderUnit? production.PUnitCode: production.UnitCode, item.Qty,DateTime.Now.ToString("yyyy-MM-dd"),item.Note,item.AutoId, frowtype, saleorg));
            }
            string json = String.Format(jsonHead, DateTime.Now.ToString("yyyy-MM-dd"), main.Retail, sb.ToString(), main.Note, main.Code,main.AutoId, saleorg);
            string filename = DateTime.Now.ToString("yyyyMMddHHmmss") + json.GetHashCode().ToString() + new Random().Next(0, 100).ToString();
            FileInfo file = new FileInfo(Path.GetDirectoryName(this.GetType().Assembly.Location) + "\\bdg\\" + filename);
            var fs = file.Create();
            var b = Encoding.UTF8.GetBytes(json);

            fs.Write(b, 0, b.Length);
            fs.Flush();
            fs.Close();
            try
            {
                Process process = new Process();
                process.StartInfo.FileName = bridgePath;
                //process.StartInfo.Arguments = "\"" + json.Replace("\"", "\\\"") + "\"";
                process.StartInfo.Arguments = "-file" + filename;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardInput = true;
                process.Start();
                string s = process.StandardOutput.ReadLine();
                if (s.StartsWith("0"))
                {
                    return base.Approve(main);
                }
                else
                {
                    return new AsmObject<bool>() { Result = AmsCode.ArgNotAccept, Data = false, Message = s };
                }
            }
            catch(Exception ex)
            {
                return new AsmObject<bool>() { Result = AmsCode.InnError, Data = false, Message = ex.Message };
            }
        }
    }
}